package com.hns.tool.clone;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


/**
 * 克隆工具类
 * @author:Fisher
 * @email:zhuangcaijin@126.com
 * @version Revision 2.0.0
 */
public class CloneUtils {
	/**
	 * 深度克隆方法。参数对象必须实现序列化!
	 * @param orig 克隆对象
	 * @return 克隆后对象
	 * @throws Exception
	 * @author:Fisher
	 * @email:zhuangcaijin@126.com
	 */
	public static Object deepCopy(Object orig) throws Exception {
		// Write the object out to a byte array
		FastByteArrayOutputStream fbos = new FastByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(fbos);
		out.writeObject(orig);
		out.flush();
		out.close();

		// Retrieve an input stream from the byte array and read
		// a copy of the object back in.
		ObjectInputStream in = new ObjectInputStream(fbos.getInputStream());
		Object obj = in.readObject();

		return obj;
	}
	
	/**
	 * clone对象N份，形成数组
	 * @param 克隆对象
	 * @param size 克隆份数
	 * @return
	 * @throws Exception
	 * @author:Fisher
	 * @email:zhuangcaijin@126.com
	 */
	public static Object[] deepCopy(Object origObj,int size) throws Exception{
		if(origObj!=null && size>0){
			Object[] clonedObjs = new Object[size];
			for (int i = 0; i < size; i++) {
				clonedObjs[i] = deepCopy(origObj);
			}
			return clonedObjs;
		}
		return null;
	}

}
